/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.SettingModel;
import com.srwl.mytx.UpdateManager;
import com.srwl.mytx.activity.JoinUsActivity;
import com.srwl.mytx.activity.LoginActivity;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * settings screen
 */
public class SettingsFragment extends BaseFragment implements OnClickListener, CompoundButton.OnCheckedChangeListener {
    private static final String TAG = "SettingsFragment";

    //声音控制
    private RelativeLayout rl_switchSound;

    //震动控制
    private RelativeLayout rl_switchVibrate;

    //扬声器播放语音
    private RelativeLayout rl_switchSpeaker;

    //好友关系解除通知
    private RelativeLayout rl_switchDeleteNotify;

    private RelativeLayout rl_voiceAutoPlay;

    private RelativeLayout rl_searchUserInfo;

    private Switch soundSwitch;
    private Switch vibrateSwitch;
    private Switch speakerSwitch;
    private Switch deleteNotifySwitch;
    private Switch switchVoiceAutoPlay;
    private Switch switchSearchUserInfo;
    private Switch switchGroupModel;
    private TextView tv_version;
    private Button logoutBtn;

    private SettingModel settingsModel;
    private boolean isAsyncToService;//同步信息到服务端失败的标志
    private boolean isFirstTime = true;

    // private EMOptions chatOptions;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.em_fragment_conversation_settings, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
            return;

        rl_switchSound = getView().findViewById(R.id.rl_switch_sound);
        rl_switchVibrate = getView().findViewById(R.id.rl_switch_vibrate);
        rl_switchSpeaker = getView().findViewById(R.id.rl_switch_speaker);
        rl_switchDeleteNotify = getView().findViewById(R.id.rl_switch__delete_notification);
        rl_voiceAutoPlay = getView().findViewById(R.id.rl_voice_auto_play);
        rl_searchUserInfo = getView().findViewById(R.id.rl_search_user_info);
        deleteNotifySwitch = getView().findViewById(R.id.switch_delete_notification);
        soundSwitch = getView().findViewById(R.id.switch_sound);
        vibrateSwitch = getView().findViewById(R.id.switch_vibrate);
        speakerSwitch = getView().findViewById(R.id.switch_speaker);
        switchVoiceAutoPlay = getView().findViewById(R.id.switch_voice_auto_play);
        switchSearchUserInfo = getView().findViewById(R.id.switch_search_user_info);
        switchGroupModel = getView().findViewById(R.id.switch_group_model);
        logoutBtn = getView().findViewById(R.id.btn_logout);


        tv_version = getView().findViewById(R.id.tv_version);


        settingsModel = Helper.getInstance().getModel();
        //  chatOptions = EMClient.getInstance().getOptions();

        rl_switchSound.setOnClickListener(this);
        rl_switchVibrate.setOnClickListener(this);
        rl_switchSpeaker.setOnClickListener(this);
        rl_switchDeleteNotify.setOnClickListener(this);
        rl_voiceAutoPlay.setOnClickListener(this);
        rl_searchUserInfo.setOnClickListener(this);
        soundSwitch.setOnCheckedChangeListener(this);
        vibrateSwitch.setOnCheckedChangeListener(this);
        speakerSwitch.setOnCheckedChangeListener(this);
        deleteNotifySwitch.setOnCheckedChangeListener(this);
        switchVoiceAutoPlay.setOnCheckedChangeListener(this);
        switchSearchUserInfo.setOnCheckedChangeListener(this);
        switchGroupModel.setOnCheckedChangeListener(this);
        getView().findViewById(R.id.rl_search_group_model).setOnClickListener(this);
        //不能设置OnClickListener,OnClickListener回调在onCheckedChanged()之后了，起不到设置isAsyncToService的效果
        switchSearchUserInfo.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                isAsyncToService = true;
                return false;
            }
        });
        getView().findViewById(R.id.rl_child_lost).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                ConfirmDialog dialog = new ConfirmDialog(getActivity(), "提示", "该功能处于开发中");
                dialog.show();
            }
        });

        getView().findViewById(R.id.rl_join_us).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), JoinUsActivity.class));
            }
        });

        getView().findViewById(R.id.rl_update).setOnClickListener(this);//更新点击监听
        logoutBtn.setOnClickListener(this);


        if (settingsModel.getSettingMsgSound()) {
            soundSwitch.setChecked(true);
        } else {
            soundSwitch.setChecked(false);
        }

        if (settingsModel.getSettingMsgVibrate()) {
            vibrateSwitch.setChecked(true);
        } else {
            vibrateSwitch.setChecked(false);
        }

        if (settingsModel.getSettingMsgSpeaker()) {
            speakerSwitch.setChecked(true);
        } else {
            speakerSwitch.setChecked(false);
        }
        //读取 好友关系解除 是否通知 的信息
        if (settingsModel.getSettingDeleteMsgNotify()) {
            deleteNotifySwitch.setChecked(true);
        } else {
            deleteNotifySwitch.setChecked(false);
        }

        if (settingsModel.getSettingVoiceAutoPlay()) {
            switchVoiceAutoPlay.setChecked(true);
        } else {
            switchVoiceAutoPlay.setChecked(false);
        }
        //设置里面的频率使用并不高，没必要中间再加一个Dao 层并缓存设置信息
        isAsyncToService = false;
        if (UserProfileManager.getInstance().getLoginUserInfo().getStatus() == Constant.USER_STATUS_HIDE_PHONE) {
            switchSearchUserInfo.setChecked(true);
        } else {
            switchSearchUserInfo.setChecked(false);//默认就是 false ,不设置也可以的
        }
        tv_version.setText(getVersionName());

        if (settingsModel.getSettingContactGroup()) {
            switchGroupModel.setChecked(true);
        } else {
            switchGroupModel.setChecked(false);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {


            case R.id.rl_switch__delete_notification:
                if (deleteNotifySwitch.isChecked()) {
                    deleteNotifySwitch.setChecked(false);

                } else {
                    deleteNotifySwitch.setChecked(true);

                }
                break;

            case R.id.rl_switch_sound:
                if (soundSwitch.isChecked()) {
                    soundSwitch.setChecked(false);

                } else {
                    soundSwitch.setChecked(true);

                }
                break;
            case R.id.rl_switch_vibrate:
                if (vibrateSwitch.isChecked()) {
                    vibrateSwitch.setChecked(false);

                } else {
                    vibrateSwitch.setChecked(true);

                }
                break;
            case R.id.rl_switch_speaker:
                if (speakerSwitch.isChecked()) {
                    speakerSwitch.setChecked(false);

                } else {
                    speakerSwitch.setChecked(true);
                }
                break;
            case R.id.rl_voice_auto_play:
                if (switchVoiceAutoPlay.isChecked()) {
                    switchVoiceAutoPlay.setChecked(false);
                } else {
                    switchVoiceAutoPlay.setChecked(true);

                }
                break;
            case R.id.btn_logout:
                logout();
                break;

            case R.id.rl_update:
                checkVersion();
                break;

            case R.id.rl_search_user_info:
                isAsyncToService = true;
                if (switchSearchUserInfo.isChecked()) {
                    switchSearchUserInfo.setChecked(false);
                } else {
                    switchSearchUserInfo.setChecked(true);
                }
                break;
            case R.id.rl_search_group_model:

                if (switchGroupModel.isChecked()) {
                    switchGroupModel.setChecked(false);
                } else {
                    switchGroupModel.setChecked(true);
                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {

            case R.id.switch_sound:
                settingsModel.setSettingMsgSound(isChecked);
                break;
            case R.id.switch_vibrate:
                settingsModel.setSettingMsgVibrate(isChecked);
                break;
            case R.id.switch_speaker:
                settingsModel.setSettingMsgSpeaker(isChecked);
                break;

            case R.id.switch_delete_notification:
                settingsModel.setSettingDeleteMsgNotify(isChecked);
                break;

            case R.id.switch_voice_auto_play:
                settingsModel.setSettingVoiceAutoPlay(isChecked);
                break;

            case R.id.switch_search_user_info:
                // settingsModel.setSettingSearchUserInfo(isChecked);

                if (isAsyncToService) {
                    setSearchUserInfo(isChecked);
                }

                break;
            case R.id.switch_group_model:
                settingsModel.setSettingContactGroup(isChecked);
                //修改模式后 通知联系人列表改变
                LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(new Intent(Constant.ACTION_CONTACT_GROUP_MODEL_CHANGED));
        }

    }

    private void setSearchUserInfo(final boolean isHide) {
//        final ProgressDialog pd = new ProgressDialog(getActivity());
//        pd.setContent("正在同步服务端设置...");
//        pd.setCanceledOnTouchOutside(false);
//        pd.show();

        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            recoverSwitchSearchUserInfo(isHide);
            return;
        }

        User updateUser = new User();
        if (isHide) {
            updateUser.setStatus(Constant.USER_STATUS_HIDE_PHONE);
        } else {
            updateUser.setStatus(Constant.USER_STATUS_NORMAL);
        }

        RetrofitManager.getInstance().createRequest(UserService.class)
                .updateUserInfo(updateUser)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        //   pd.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "更新设置失败：" + response.message());
                            showToast(rl_searchUserInfo, getString(R.string.system_busy));
                            recoverSwitchSearchUserInfo(isHide);
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "更新设置失败：" + result.getMsg());
                            showToast(rl_searchUserInfo, getString(R.string.system_busy));
                            recoverSwitchSearchUserInfo(isHide);
                            return;
                        }
                        if (isHide) {
                            showToast(rl_searchUserInfo, "隐身模式已开启，其他人不能通过手机号添加你");
                        } else {
                            showToast(rl_searchUserInfo, "隐身模式已关闭，其他人可以通过手机号添加你");
                        }
                        //  PreferenceManager.getInstance().setSearchUserInfo(isHide);
                        UserProfileManager.getInstance().setStatus(updateUser.getStatus());

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        //  pd.dismiss();
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(rl_searchUserInfo, getString(R.string.system_busy));
                        recoverSwitchSearchUserInfo(isHide);
                    }
                });

    }

    /**
     * 当同步设置到服务端失败后，恢复到之前的设置
     *
     * @param isCanSearch
     */
    void recoverSwitchSearchUserInfo(boolean isCanSearch) {
        isAsyncToService = false;
        switchSearchUserInfo.setChecked(!isCanSearch);
    }

    private void checkVersion() {
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getVersion()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "获取版本失败：" + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "获取版本失败：" + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        JSONObject versionInfo = (JSONObject) result.getData();
                        if (versionInfo == null || versionInfo.size() == 0) {
                            return;
                        }
                        if (versionInfo.getBigInteger("version") == null || versionInfo.getString("apk_url") == null || versionInfo.getString("updateLog") == null) {
                            return;
                        }
                        Log.d(TAG, "获取版本信息完成：" + versionInfo);
                        int serviceVersion = versionInfo.getInteger("version");
                        String updateLog = versionInfo.getString("updateLog");
                        String apkUrl = versionInfo.getString("apk_url");
                        updateLog = updateLog.replace("|", "\n");
                        UpdateManager manager = new UpdateManager(serviceVersion, apkUrl, updateLog, getActivity());
                        manager.setInteractionInterface(new UpdateManager.InteractionInterface() {
                            @Override
                            public void showToast(String content) {
                                SettingsFragment.this.showToast(content);
                            }
                        });
                        manager.checkUpdate();


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "获取版本失败：" + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }

    void logout() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        final ProgressDialog pd = new ProgressDialog(getActivity());
        String st = getResources().getString(R.string.Are_logged_out);
        pd.setMessage(st);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        JSONObject body = new JSONObject();
        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
        RetrofitManager.getInstance().createRequest(UserService.class)
                .logout(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        pd.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            pd.dismiss();
                            Log.e(TAG, "登出出错：" + response.message());
                            //showToast("退出出错，稍后再试");
                            // return;
                        } else if (result.isError()) {
                            pd.dismiss();
                            Log.e(TAG, "登出出错:" + result.getMsg());
                            // showToast("退出出错，稍后再试");
                            // return;
                        } else {

                            Log.d(TAG, "个人服务端登出完成");
                        }

                        Helper.getInstance().logout();
                        //非临时用户的时候，退出登录时清除掉已经打开的activity
                        if (!Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                            MyApplication.getInstance().finishActivities();
                        }
                        startActivity(new Intent(getActivity(), LoginActivity.class));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        pd.dismiss();
                        Log.e(TAG, "登出出错:" + t.getMessage());
                        showToast("退出出错，稍后再试");
                    }
                });


    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    private String getVersionName() {
        try {
            PackageManager manager = getActivity().getPackageManager();

            PackageInfo info = manager.getPackageInfo(getActivity().getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return this.getString(R.string.can_not_find_version_name);
        }
    }


//    @Override
//    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
//        if (((MainActivity) getActivity()).isConflict) {
//            outState.putBoolean("isConflict", true);
//        } else if (((MainActivity) getActivity()).getCurrentAccountRemoved()) {
//            outState.putBoolean(Constant.ACCOUNT_REMOVED, true);
//        }
//    }
}
